package logic

import (
	"context"
	"encoding/json"
	"fresh/freshrpc/freshrpc"
	"fresh/freshrpc/internal/svc"
	"fresh/modesl/cache"
	"fresh/modesl/mysql"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
)

type FreshListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshListLogic {
	return &FreshListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FreshListLogic) FreshList(in *freshrpc.FreshListRequest) (*freshrpc.FreshListResponse, error) {
	// todo: add your logic here and delete this line

	res, _ := cache.Rdb.Get(l.ctx, "goodsList").Result()
	goods := mysql.Goods{}
	if res == "" {
		mysql.DB.Debug().Table("goods").Select("goods.*").Find(&goods)
		jsonData, _ := json.Marshal(&goods)
		cache.Rdb.Set(l.ctx, "goodsList", jsonData, time.Minute*30)
	}

	return &freshrpc.FreshListResponse{
		Title: goods.Title,
		Image: goods.Image,
		Price: uint64(goods.Price),
	}, nil
}
